package com.yonyou.cyxdms.sysAuth.service.controller.manage.role;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoleilu.hutool.util.StrUtil;
import com.yonyou.cyx.framework.controller.base.BaseController;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.CommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.CodeDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.CommonTreeDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.role.RolePDto;
import com.yonyou.cyxdms.sysAuth.service.entity.role.RolePO;
import com.yonyou.cyxdms.sysAuth.service.mapper.PermissionMenuMapper;
import com.yonyou.cyxdms.sysAuth.service.service.manage.employee.EmployeeService;
import com.yonyou.cyxdms.sysAuth.service.service.permission.PermissionCtrlService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleCtrlService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleMenuActionService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleMenuRangeService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleService;
import com.yonyou.cyxdms.sysAuth.service.vo.role.RolePageVO;
import com.yonyou.cyxdms.sysAuth.service.vo.role.RoleVO;
import com.yonyou.cyxdms.sysmanage.client.vo.role.UserbyRoleVO;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色管理
 *
 * @author adu
 * @since 2019/9/23
 */
@Api(value = "角色管理", tags = {"角色管理"})
@RestController
@RequestMapping("/basedata/roles")
public class RoleMangeController extends BaseController {


    // 定义日志接口
    private static final Logger logger = LoggerFactory.getLogger(RoleMangeController.class);

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleCtrlService roleCtrlService;
    @Autowired
    private PermissionMenuMapper permissionMenuMapper;
    @Autowired
    private RoleMenuActionService roleMenuActionService;
    @Autowired
    private RoleMenuRangeService roleMenuRangeService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private PermissionCtrlService permissionCtrlService;

    /**
     * 添加角色信息 -ok
     *
     * @author adu
     * @since 2019/9/19
     */
    @ApiOperation(value = "新增角色")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @PostMapping
    public Map<String, Object> addRole(@RequestBody RolePDto rolepdto) {
        return roleService.addRole(rolepdto);
    }

    /**
     * 分页条件查询角色-ok
     *
     * @author adu
     * @since 2019/9/19
     */
    @ApiOperation(value = "角色权限管理-列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @GetMapping
    public IPage<RolePageVO> queryOperateLog(@RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                             @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                             String roleCode, String roleName,Integer roleType, Integer positionCode, Integer type) {
        Page<RolePageVO> page = new Page(currentPage, pageSize);
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryCondition = new HashMap<>();
        queryCondition.put("userId", loginInfoDto.getUserId());
        queryCondition.put("appId", loginInfoDto.getAppId());
        // queryCondition.put("dataType", loginInfoDto.getDataType());
        queryCondition.put("companyId", loginInfoDto.getCompanyId());
        queryCondition.put("roleCode", roleCode);
        queryCondition.put("roleName", roleName);
        queryCondition.put("roleType", roleType);
        queryCondition.put("positionCode", positionCode);
        queryCondition.put("typePar", type);//厂端维护的经销商角色显示（type=1）
        if (type == null) {
            queryCondition.put("dataType", ManageDictCodeConstants.DATA_TYPE_BY_SUPER);
        } else {
            queryCondition.put("dataType", ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
        }
        return roleService.queryRole(page, queryCondition);
    }

    /**
     * 删除角色及对应权限
     * 删除需判断此角色是否有员工正在使用中，如果有，不能删除，提示：此角色已被使用，不能删除
     *
     * @author adu
     * @since 2019/9/19
     */
    @ApiOperation(value = "删除角色")
    @DeleteMapping(value = "/deleteById/{id}")
    @ResponseStatus(HttpStatus.OK)
    public Integer deleteBrand(@PathVariable("id") Integer id) {
        return roleService.deleteRoleById(Long.valueOf(id));
    }


    /**
     * 通过角色id 查询roleCode，roleName
     */
    @GetMapping("/queryByRoleId/{roleId}")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "员工id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "通过角色id 查询roleCode/roleName")
    public List<Map<String, String>> queryByRoleId(@PathVariable Integer roleId) {
        return roleService.queryByRoleId(roleId);
    }

    /**
     * 角色对应的权限的新增及修改
     *
     * @author adu
     * @since 2019/9/20
     */
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "编辑角色权限（配置角色权限）")
    @PutMapping(value = "/permission")
    public ResponseEntity<RolePDto> modifyOrg(@RequestBody RolePDto rolepdto) {
        roleService.modifyOrg(rolepdto);
        MultiValueMap<String, String> headers = new HttpHeaders();
        return new ResponseEntity<>(headers, HttpStatus.OK);
    }


    /**
     * 角色属性：销售
     *
     * @author ：adu
     * @date ：2019/9/20
     * @description：
     */
    @ApiOperation(value = "角色属性:(销售1006)（大区经理：1099）")
    @ApiImplicitParams({@ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")})
    @RequestMapping(value = "/findRoleByType/{id}", method = RequestMethod.GET)
    public List<CodeDTO> findTcCodeByType(@PathVariable("id") Long id) {
        return employeeService.findTcCodeByType(id);
    }


    /**
     * 角色属性：售后
     *
     * @author ：adu
     * @date ：2019/9/20
     * @description：
     */
    @ApiOperation(value = "角色属性:(售后1007)")
    @ApiImplicitParams({@ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")})
    @RequestMapping(value = "/findRoleBySale/{id}", method = RequestMethod.GET)
    public List<CodeDTO> findRoleBySale(@PathVariable("id") Long id) {
        return employeeService.findTcCodeByType(id);
    }

    /**
     * 菜单：维修
     *
     * @author ：adu
     * @date ：2019/9/20
     * @description：
     */
    @ApiOperation(value = "个人参数配置(维修:1211)")
    @ApiImplicitParams({@ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")})
    @RequestMapping(value = "/findRoleByRepair/{id}", method = RequestMethod.GET)
    public List<CodeDTO> findRoleByRepair(@PathVariable("id") Long id) {
        Integer permissionType = ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE;
        return employeeService.findTcCodeByType(id);
    }


    /**
     * 菜单：配件
     *
     * @author ：adu
     * @date ：2019/9/20
     * @description：
     */
    @ApiOperation(value = "个人参数配置（配件:1313)")
    @ApiImplicitParams({@ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")})
    @RequestMapping(value = "/findRoleByParts/{id}", method = RequestMethod.GET)
    public List<CodeDTO> findRoleByParts(@PathVariable("id") Long id) {
        Integer permissionType = ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE;
        return employeeService.findTcCodeByType(id);
    }


    /**
     * 加载角色权限信息
     *
     * @author adu
     * @since 2019/8/28
     */
    @ApiOperation(value = "加载角色权限信息")
    @GetMapping(value = "/roleData")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ResponseBody
    public Map<String, Object> roleDataMap(@RequestParam String roleId) {
        logger.debug("===================================>>>>>>>>>>>>>>>>111111");
        Integer isFixed = roleService.isFixed();
        if (null == isFixed) {
            isFixed = 10041002;
        }
//        String id = null;
////        if (!StringUtils.isNullOrEmpty(queryParam.get("roleId"))) {
////            id = queryParam.get("roleId").toString();
////        }
        return getRoleData(roleId, isFixed);
    }


    /**
     * 保存角色权限
     *
     * @author adu
     * @since 2019/9/21
     */
    @ApiOperation(value = "根据RoleId查询菜单")
    @GetMapping(value = "/roleData/{id}")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ResponseBody
    public Map<String, Object> roleData(@PathVariable(value = "id") String id) {

        logger.debug("===================================>>>>>>>>>>>>>>>>222222222");

        Integer isFixed = roleService.isFixed();

        return getRoleData(id, isFixed);

    }


    /**
     * 查询角色受控权限（维修） 复选框组(查tc_code)
     *
     * @param ids
     * @return
     * @author adu
     * @date 2019/09/20
     */
    @ApiOperation(value = "维修")
    @RequestMapping(value = "/roleMaintain/{id}", method = RequestMethod.GET)
    @ResponseBody
    public List<CodeDTO> maintainRemoteUrl(@PathVariable(value = "id") String ids) {
        return permissionCtrlService.maintainRemoteUrl(ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, ids);
    }

    /**
     * 查询角色受控权限（配件） 复选框组
     *
     * @param ids
     * @return
     * @author maxingjian
     * @date 2019/07/12
     */
    @ApiOperation(value = "配件")
    @GetMapping(value = "/roleAccessories/{id}")
    @ResponseBody
    public List<CodeDTO> accessoriesRemoteUrl(@PathVariable(value = "id") String ids) {
        return permissionCtrlService.accessoriesRemoteUrl(ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, ids);
    }


    /**
     * 角色新增页面初始化数据
     *
     * @author dengqiang
     * @since 2019/7/24
     */
    @GetMapping(value = "/roleDataAdd/{dataType}")
    @ResponseBody
    public Map<String, Object> roleDatadd(@PathVariable(value = "dataType") Integer dataType) {
        List<Map<String, Object>> list = roleService.queryMenu(dataType);
        List<CommonTreeDTO> orgList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            CommonTreeDTO orgTreeOrg = new CommonTreeDTO();
            orgTreeOrg.setId(list.get(i).get("MENU_ID").toString());
            String parent = list.get(i).get("PARENT_ID").toString();
            if ("0".equals(parent)) {
                parent = "#";
            }
            orgTreeOrg.setParent(parent);
            orgTreeOrg.setText(list.get(i).get("MENU_NAME").toString());
            orgList.add(orgTreeOrg);
        }
        Map<String, Object> roleData = new HashMap<>();
        Map<String, String> checkbox = new HashMap<>();
        String[] treeMenuActionString = new String[0];
        String[] treeMenuRangeString = new String[0];
        roleData.put(CommonConstants.TREEJSON, orgList);
        roleData.put(CommonConstants.CHECKBOX, checkbox);
        roleData.put(CommonConstants.TREE_MENU_ACTION, treeMenuActionString);
        roleData.put(CommonConstants.TREE_MENU_RANGE, treeMenuRangeString);
        return roleData;
    }

    /**
     * 查询角色菜单数据范围权限  复选框组
     * 1037
     *
     * @author adu
     * @since 2019/9/23
     */
    @ApiOperation(value = "角色菜单数据范围权限 操作权限")
    @GetMapping(value = "/roleMenuRange/{menuId}/{roleIds}")
    @ResponseBody
    public List<Map<String, Object>> rangeRemoteUrl2(@PathVariable(value = "menuId") Long menuId, @PathVariable(value = "roleIds") String roleIds) {
        Integer isFixed = roleService.isFixed();
        Integer permissionType = ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE;
        if (StringUtils.isEquals(10041001, isFixed.toString())) {
            return roleMenuRangeService.remoteSoftUrl(menuId, permissionType, roleIds);
        } else {
            return roleMenuRangeService.remoteUrl(menuId);
        }
    }


    /**
     * 查询角色菜单操作按钮 复选框组
     *
     * @author adu
     * @since 2019/9/23
     */
    @ApiOperation(value = "角色菜单数据范围权限  操作按鈕")
    @GetMapping(value = "/roleMenuAction/{menuId}/{roleIds}")
    @ResponseBody
    public List<Map<String, Object>> actionRemoteUrl(@PathVariable(value = "menuId") Long menuId, @PathVariable(value = "roleIds") String roleId) {
        Integer isFixed = roleService.isFixed();
        Integer permissionType = ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE;
        if (StringUtils.isEquals(10041001, isFixed.toString())) {
            return roleMenuActionService.remoteSoftUrl(menuId, permissionType, roleId);
        } else {
            return roleMenuActionService.remoteUrl(menuId);
        }

    }


    /**
     * 角色权限
     *
     * @param id
     * @param isFixed
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author dengqiang
     * @since 2019/8/1
     */
    public Map<String, Object> getRoleData(String id, Integer isFixed) {

        Map<String, String> checkbox = roleCtrlService.queryMenuCtrl(ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, id);//you
        List<CommonTreeDTO> orgList = roleService.querygfkmenu(id);
        Map<String, Object> roleData = new HashMap<>();
        roleData.put(CommonConstants.TREEJSON, orgList);
        roleData.put(CommonConstants.CHECKBOX, checkbox);
        roleData.put(CommonConstants.TREE_MENU_ACTION, roleMenuActionService.findMenuAction(ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, id));
        roleData.put(CommonConstants.TREE_MENU_RANGE, roleMenuRangeService.findMenuRange(ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, id));
        roleData.put("isFixed", isFixed);
        return roleData;
    }


    /**
     * 通过角色类别查询用户信息
     *
     * @author 马邢健
     * @since 2019/9/18
     */
    @GetMapping(value = "/getUserInfoByRolePosition")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "通过角色类别查询用户信息")
    public List<UserbyRoleVO> getUserInfoByRolePosition(@ApiParam(name = "positionCode", value = "角色类别", required = false) @RequestParam(required = false, defaultValue = "") String positionCode,
                                                        @ApiParam(name = "role", value = "角色类别", required = false) @RequestParam(required = false, defaultValue = "") String role,
                                                        @ApiParam(name = "companyId", value = "公司ID", required = false) @RequestParam(required = false, defaultValue = "") String companyId,
                                                        @ApiParam(name = "ownerCode", value = "经销商编号", required = false) @RequestParam(required = false, defaultValue = "") String ownerCode) {
        String param = null;
        if(StrUtil.isEmpty(positionCode) && StrUtil.isNotEmpty(role)){
            param = role;
        }
        if(StrUtil.isEmpty(role) && StrUtil.isNotEmpty(positionCode)){
            param = positionCode;
        }
        return roleService.getUserInfoByRolePosition(param, companyId, ownerCode);
    }

    /**
     * 通过角色类别查询用户信息
     *
     * @author 马邢健
     * @since 2019/9/18
     */
    @GetMapping(value = "/getUserInfoByRole")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "通过角色查询用户信息")
    public List<UserbyRoleVO> getUserInfoByRole(@ApiParam(name = "roleCode", value = "角色", required = true) @RequestParam String roleCode,
                                                @ApiParam(name = "companyId", value = "公司id", required = false) @RequestParam(value = "companyId", required = false, defaultValue = "") String companyId) {
        return roleService.getUserInfoByRole(roleCode, companyId);
    }


    /**
     * 获取厂端角色
     *
     * @author 马邢健
     * @since 2019/9/18
     */
    @GetMapping(value = "/getRole")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "获取厂端角色")
    public List<RolePO> getRole(@ApiParam(name = "companyId", value = "公司ID", required = true) @RequestParam Long companyId) {
        return roleService.getRole(companyId);
    }

    /**
     * 获取厂端预置的所有角色
     *
     * @author 李贺
     * @since 2019/11/18
     */
    @GetMapping(value = "/getPresetRole")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "获取厂端预置的所有角色")
    public List<RoleVO> getPresetRole() {
        return roleService.getPresetRole();
    }



    /**
     * 通过角色名称获取角色信息
     *
     * @author 李贺
     * @since 2019/11/18
     */
    @PostMapping("/getPresetRoleByName")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "过角色名称获取角色信息")
    public List<RoleVO> getPresetRoleByName(@RequestBody List<String> names) {
        return roleService.getPresetRoleByName(names);
    }
}
